<template>
    <transition name="el-fade-in-linear">
    <div id="mainPage">
        <el-container style="height: 100%;">
            <el-header height="61px" class="header-style">
                <div class="title-style">
                    <img src="../../../resources/assets/login/cc.png"  alt="周报"/>
                    <span  v-model="title" class="ft18p clr-dk-sp4 cursorLink" style="font-weight: 900;" @click="toWelcomePath()">交付资产库信息查询系统</span>
                </div>
                <div class="icon-style">
<!--                    <img src="../../../resources/assets/nav/UserIcon.png"/>-->
                </div>
                <el-dropdown class="nameHover">
              <span class="el-dropdown-link clr-dk-sp5 ft14p nameCursor">
                {{userName}}<i class="el-icon-arrow-down el-icon--right"></i>
              </span>
                    <el-dropdown-menu slot="dropdown">
                        <el-dropdown-item><el-button type="text" @click="modifyPasswordButton('formForPassword')">修改密码</el-button></el-dropdown-item>
                        <el-dropdown-item><el-button type="text" @click="getDialogFormUserInfo">账户信息</el-button></el-dropdown-item>
                    </el-dropdown-menu>
                </el-dropdown>
                <div class="icon-style cursorLink">
                    <img src="../../../resources/assets/nav/signout.png" @click="signout"/>
                </div>
            </el-header>
            <el-container>
                <el-aside width="200px" class="nav-style">
                    <el-row id="nav" class="tac">
                        <el-col style="width: 200px;">
                            <el-menu
                                    :default-active="activeIndex"
                                    class="el-menu-vertical-demo"
                                    @open="handleOpen"
                                    @close="handleClose"
                                    text-color="#fff"
                                    active-text-color="#ffffff"
                                    :unique-opened=true
                                    @select="activeAction">
                                <div v-for="item in menuList">
                                    <el-submenu :index="item.index"  v-if="hasSub(item)" :class="activeIndex === item.index?'activeLine':''">
                                        <template slot="title">
                                            <img :src="item.src" class="nav-img" alt=""/>
                                            <span  class="ft16p ml5 ">{{item.title}}</span>
                                        </template>
                                        <nav-cpt class="nav-self" :data="item" :activeIndex="activeIndex"></nav-cpt>
                                    </el-submenu>
                                    <el-menu-item :index="item.index"  v-else-if="!hasSub(item)" :class="activeIndex === item.index?'activeLine':''">
                                        <img :src="item.src" class="nav-img" alt=""/>
                                        <span slot="title" class="ft16p ml5">{{item.title}}</span>
                                    </el-menu-item>
                                </div>
                            </el-menu>
                        </el-col>
                    </el-row>
                </el-aside>
                <el-main class="main-style">
                    <transition name="el-fade-in-linear">
                        <router-view>
                        </router-view>
                    </transition>
                </el-main>
            </el-container>
        </el-container>
        <el-dialog title="修改密码" :visible.sync="dialogFormChangePassword">
            <el-form ref="formForPassword" :model="formForPassword"  :rules="formRules">
                <el-form-item label="原始密码" :label-width="formLabelWidth"  prop="oldPassword">
                    <el-input type="password" v-model.trim="formForPassword.oldPassword" autocomplete="off" placeholder="请输入原始密码"></el-input>
                </el-form-item>
                <el-form-item label="新密码" :label-width="formLabelWidth"  prop="newPassword">
                    <el-input type="password" v-model.trim="formForPassword.newPassword" autocomplete="off" placeholder="请输入新密码"></el-input>
                </el-form-item>
                <el-form-item label="再次输入" :label-width="formLabelWidth"  prop="renewPassword">
                    <el-input type="password" v-model.trim="formForPassword.renewPassword" autocomplete="off" placeholder="请再次输入新密码"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormChangePassword = false">取 消</el-button>
                <el-button type="primary" @click="changePassword('formForPassword')">确 定</el-button>
            </div>
        </el-dialog>
        <el-dialog title="账户信息" :visible.sync="dialogFormUserInfo">
            <el-form>
                <el-form-item label="账号:" :label-width="formLabelWidth">
                    <span>{{accountName}}</span>
                </el-form-item>
                <el-form-item label="用户名:" :label-width="formLabelWidth"  prop="userName">
                    <span>{{userName}}</span>
                </el-form-item>
                <el-form-item label="所属角色:" prop="roleIdList" :label-width="formLabelWidth">
                        <span class="mr5">
                            <el-tag :key="tag.id" v-for="tag in roleIdList" class="mr5" type="info">
                                {{tag.roleName}}
                            </el-tag>
                        </span>
                </el-form-item>
                <el-form-item label="所属组:" prop="groupIdList" :label-width="formLabelWidth">
                        <span class="mr5">
                            <el-tag :key="tag.id" v-for="tag in groupIdList" class="mr5" type="info">
                                {{tag.groupName}}
                            </el-tag>
                        </span>
                </el-form-item>
                <el-form-item label="用户说明:" :label-width="formLabelWidth"  prop="oldPassword">
                    <span>{{summary}}</span>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormUserInfo = false">取 消</el-button>
                <el-button type="primary" @click="dialogFormUserInfo = false">确 定</el-button>
            </div>
        </el-dialog>
    </div>
    </transition>
</template>

<script>
    import Vue from 'vue';
    import NavCpt from "../../components/navCpt/navCpt.vue";
    import urlConfig from "../../config/url.json"
    import axios from 'axios';
    import { Message } from 'element-ui';

    Vue.component(Message.name, Message);

    // Vue.component(Message.name, Message);

    let modifyPasswordUrl=urlConfig.modifyPassword;
    let viewUrl = urlConfig.viewUser;
    let getGroupAfterUserUrl = urlConfig.getGroupAfterUser;
    let productUrl=urlConfig.validProduct;
    let projectUrl=urlConfig.validProject;
    let taskUrl=urlConfig.validTask;


    export default {
        components: {
            NavCpt
        },
        data(){
            var validatePass2 = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请再次输入密码'));
                } else if (value !== this.formForPassword.newPassword) {
                    callback(new Error('两次输入的新密码不一致!'));
                } else {
                    console.log('密码不一致');
                }
                callback();
            };
            var validatePass1 = (rule,value,callback) =>{
                if(value !== this.storagePassword){
                    callback(new Error('输入的原密码不正确！'));
                }
                callback();
            };
            return{
                title:"",
                menuList:[],
                returnData:[],
                dialogFormChangePassword: false,
                dialogFormUserInfo: false,
                formForPassword: {
                    oldPassword: '',
                    newPassword: '',
                    renewPassword: '',
                },
                roleIdList:[],
                groupIdList:[],
                formLabelWidth: '100px',
                summary:'',
                storagePassword:'',
                accountName:'',
                userName:'',
                id:'',
                formRules: {
                    oldPassword: [
                        { validator: validatePass1,trigger:'blur'},
                        { required: true,message:'请输入旧的密码' },
                        { max: 10, message: '最长10个字符', trigger: 'blur' }
                    ],
                    newPassword: [
                        { required: true,message:'请输入新的密码' },
                        { max: 10, message: '最长10个字符', trigger: 'blur' }
                    ],
                    renewPassword: [
                        { validator: validatePass2, trigger: 'blur' }
                    ]
                },
                productTreeData: [],

            }
        },
        mounted(){
            let that = this;
            that.id = JSON.parse(that.STORAGE.getItem("loginData"))['id'];
            that.userName = JSON.parse(that.STORAGE.getItem("loginData"))['username'];
            that.accountName = JSON.parse(that.STORAGE.getItem("loginData"))['accountname'];
            that.storagePassword = JSON.parse(that.STORAGE.getItem("loginData"))['password'];
            let paramsForIsShow = {
                userId:this.id,
                enable:1,
                ifShow:1
            };
            that.queryUser();
            that.queryProject();
            that.queryProduct();
            that.getUserInfo();
            that.queryTask();

            that.$options.methods.getMenuForIsShow(paramsForIsShow,that);

        },
        computed:{
            activeIndex:function () {
                return this.$store.state.menuIndex;
            }
        },
        methods: {
            getProductJsonTree(newdata,parentId){

                let that = this;
                let itemArr=[];
                for(let i=0;i<newdata.length;i++){
                    let node=newdata[i];
                    if(node.parentId==parentId ){
                        let newNode={
                            value:node.id,
                            label:node.productName,
                        };
                        if(that.getProductJsonTree(newdata,node.id).length!=0){
                            newNode.children = that.getProductJsonTree(newdata,node.id);
                        }
                        itemArr.push(newNode);
                    }
                }
                itemArr.sort(that.up);
                return itemArr;
            },
            queryProduct(){
                let that=this;
                const loading = this.$loading({
                    lock: true,
                    text: 'Loading',
                    spinner: 'el-icon-loading',
                });
                that.$http({
                    method: 'get',
                    url: productUrl,
                    baseURL:'/api',
                    params:{
                        'id':'',
                    }
                }).then(function(response){
                    if(response.data.code==200){
                        var productList=response.data.data.dcProductList;
                        that.productTreeData =that.getProductJsonTree(productList, '-1');
                        // var arr = new Array();
                        // for(var i=0 ;i<productList.length;i++){
                        //     var productObject = {'code':productList[i]['id'],'value':productList[i]['productName']};
                        //     arr.push(productObject)
                        // }
                        that.STORAGE.setItem("productAll",JSON.stringify(that.productTreeData));
                    }
                    else{
                        Message.error('获取有效产品数据失败');
                    }
                    loading.close();
                }).catch(function(err){
                    console.log(err);
                    Message.error('获取数据失败');
                    loading.close();
                });
            },
            
            queryProject(){
                let that=this;
                const loading = this.$loading({
                    lock: true,
                    text: 'Loading',
                    spinner: 'el-icon-loading',
                });
                that.$http({
                    method: 'get',
                    url: projectUrl,
                    baseURL:'/api',
                    params:{
                        'projectName':'',
                        'stateValue':'-1',
                    }
                }).then(function(response){
                    if(response.data.code==200){
                        var projectList=response.data.data.dcProjectList;
                        var arr = new Array();
                        for(var i=0 ;i<projectList.length;i++){
                            var projectObject = {'code':projectList[i]['id'],'value':projectList[i]['projectName']};
                            arr.push(projectObject);
                        }
                        that.STORAGE.setItem("projectAll",JSON.stringify(arr));
                    }
                    else{
                        Message.error('获取数据失败');
                    }
                    loading.close();
                }).catch(function(err){
                    console.log(err);
                    Message.error('获取数据失败');
                    loading.close();
                });

            },

            queryTask(){
                let that=this;
                const loading = this.$loading({
                    lock: true,
                    text: 'Loading',
                    spinner: 'el-icon-loading',
                });
                that.$http({
                    method: 'get',
                    url: taskUrl,
                    baseURL:'/api',
                    params:{
                        'taskName':'',
                        'stateValue':'-1',
                    }
                }).then(function(response){
                    if(response.data.code==200){
                        var taskList=response.data.data.dcTaskList;
                        var arr = new Array();
                        for(var i=0 ;i<taskList.length;i++){
                            var taskObject = {'code':taskList[i]['id'],'value':taskList[i]['taskName']};
                            arr.push(taskObject);
                        }
                        that.STORAGE.setItem("TaskAll",JSON.stringify(arr));
                    }
                    else{
                        Message.error('获取数据失败');
                    }
                    loading.close();
                }).catch(function(err){
                    console.log(err);
                    Message.error('获取数据失败');
                    loading.close();
                });

            },



            queryUser(){
                let that=this;
                const loading = this.$loading({
                    lock: true,
                    text: 'Loading',
                    spinner: 'el-icon-loading',
                });
                that.$http({
                    method: 'get',
                    url: getGroupAfterUserUrl,
                    baseURL:'/api',
                    params:{
                        'id':JSON.parse(that.STORAGE.getItem("loginData"))['id']
                    }
                }).then(function(response){
                    if(response.data.code==200){
                        that.STORAGE.setItem("userAll",JSON.stringify(response.data.data.usermapList));
                        if(response.data.data.department.length==1){
                            that.title="健康云平台周报管理系统";
                        }else{
                            that.title=response.data.data.department + "周报管理系统";
                        }

                        that.STORAGE.setItem("department",response.data.data.department);
                        that.STORAGE.setItem("noWeekGroupList",response.data.data.noWeekGroupList);
                    }
                    else{
                        Message.error('获取数据失败');
                    }
                    loading.close();
                }).catch(function(err){
                    console.log(err);
                    Message.error('获取数据失败');
                    loading.close();
                });
            },
            modifyPasswordButton(formName){
                let that = this;
                if(that.$refs[formName]){
                    that.$nextTick(()=>{
                        that.$refs[formName].clearValidate();
                        that.$refs[formName].resetFields();
                    });
                }
                that.dialogFormChangePassword = true;
            },
            changePassword(formName){
                let that = this;
                that.$refs[formName].validate((valid) => {
                    if (valid) {
                        const loading = this.$loading({
                            lock: true,
                            text: 'Loading',
                            spinner: 'el-icon-loading',
                        });
                        that.$http({
                            method: 'put',
                            url: modifyPasswordUrl,
                            baseURL:'/api',
                            data:{
                                'id':that.id,
                                'accountName':that.accountName,
                                'oldPassword':that.formForPassword.oldPassword,
                                'newPassword':that.formForPassword.newPassword,
                            }
                        }).then(function(response){
                            if(response.data.code==200){
                                that.dialogFormChangePassword = false;
                                Message.success('修改密码成功,请重新登录');
                                that.STORAGE.clear();
                                that.$router.push('../login');
                            }
                            else{
                                Message.error('修改密码失败');
                            }
                            loading.close();
                        }).catch(function(err){
                            console.log(err);
                            Message.error('修改密码失败');
                            loading.close();
                        });

                    } else {
                        return false;
                    }

                });

            },

            handleOpen(key, keyPath) {
                // console.log(key, keyPath);
            },
            handleClose(key, keyPath) {
                // console.log(key, keyPath);
            },

            hasSub(item){
                if(item['subMenuList'] !=undefined && item['subMenuList']  != ''){
                    return true;
                }else{
                    return false;
                }
            },
            getJsonTree(data,parentId,that){
                let itemArr=[];
                for(let i=0;i<data.length;i++){
                    let node=data[i];
                    //data.splice(i, 1)
                    if(node.parentId==parentId ){
                        let newNode={
                            id:node.id,
                            title:node.name,
                            index:node.id.toString(),
                            src:node.icon,
                            path:node.path,
                            orderid:node.orderid,
                            subMenuList:that.$options.methods.getJsonTree(data,node.id,that)
                        };
                        itemArr.push(newNode);
                    }
                }
                itemArr.sort(that.$options.methods.up);
                return itemArr;
            },

            up(x,y){
                return x.orderid-y.orderid
            },
            activeAction(index){
                // this.activeIndex = index;
                for(let i = 0; i < this.returnData.length; i++){
                    if(this.returnData[i]["id"] == index){
                        this.$router.push(this.returnData[i]["path"]);
                        // this.$router.push('/mainPage/test');
                        break;
                    }
                }
            },
            signout(){
                let that=this;
                var path ='';
                that.$confirm('是否退出登录', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    that.STORAGE.clear();
                    if(!that.quitLogin){
                        that.$router.push( '../../login');
                    }else{
                        that.$router.push( '../login');
                    }
                    // window.onbeforeunload = function (e) {
                    //     var storage = window.localStorage;
                    //     storage.clear()}
                }).catch(() => {
                    that.$message({
                        type: 'info',
                        message: '已取消退出登录'
                    });
                });
            },

            getDialogFormUserInfo(){
                let that = this;
                that.getUserInfo();
                that.dialogFormUserInfo = true;
            },
            getUserInfo(){
                let that = this;
                const loading = that.$loading({
                    lock: true,
                    text: 'Loading',
                    spinner: 'el-icon-loading',
                });
                that.$http({
                    method: 'get',
                    url: viewUrl,
                    baseURL:'/api',
                    params:{
                        'id':that.id
                    }
                }).then(function(response){
                    if(response.data.code==200){
                        that.summary = response.data.data.msUser.summary;
                        that.roleIdList = response.data.data.bgRoleList;
                        that.groupIdList = response.data.data.msGroupsList;
                        that.STORAGE.setItem("roleIdList",JSON.stringify(that.roleIdList));
                        that.STORAGE.setItem("groupIdList",JSON.stringify(that.groupIdList));
                        that.STORAGE.setItem("mainProdctList",JSON.stringify(response.data.data.dcProductList));
                    }
                    else{
                        Message.error('查看用户信息失败');
                    }
                    loading.close();
                }).catch(function(err){
                    console.log(err);
                    Message.error('查看用户信息失败');
                    loading.close();
                });
            },
            getMenuForEnable(params,that){
                that.$http({
                    method: 'get',
                    url: urlConfig.getMenuByUserId,
                    baseURL:"/api",
                    params:params
                }).then(function (response){
                    if(response.status == '200'){
                        if(response.data.menuInfos.length > 0){
                            that.STORAGE.setItem("menu",JSON.stringify(response.data.menuInfos));   /*为路由准备权限判断*/
                        }
                    }
                }).catch(function(err){

                })
            },
            getMenuForIsShow(params,that){
                let paramsForEnable = {
                    userId:that.id,
                    enable:1,
                };
                that.$http({
                    method: 'get',
                    url: urlConfig.getMenuByUserId,
                    baseURL:"/api",
                    params:params
                }).then(function (response){
                    if(response.status == '200'){
                        if(response.data.menuInfos.length > 0){
                            that.returnData = response.data.menuInfos;
                            that.menuList = that.$options.methods.getJsonTree(response.data.menuInfos,'-1',that);
                        }
                    }
                    that.getMenuForEnable(paramsForEnable,that)
                }).catch(function(err){

                })
            }

        },
    }
</script>

<style scoped>
    .nav-style {
        height: 100%;
        width: 200px;
        background-image: linear-gradient(-180deg, #2FB2B8 0%, #23BBC8 70%, #44D5B6 100%);
        box-shadow: inset -4px 0 7px 0 rgba(0,0,0,0.10);
        position: fixed;
        left: 0;
        top: 60px;
        z-index: 20;
        overflow-y: auto;
        overflow-x: hidden;
    }

    .nameHover :hover {
        color: #44D5B6;
    }
    .header-style {
        width: 100%;
        min-width: 1000px;
        text-align: right;
        font-size: 12px;
        position: fixed;
        left: 0;
        z-index: 2019;
        overflow-y: auto;
        overflow-x: hidden;
        border-bottom: 1px solid #ebeef5;
    }

    .main-style {
        margin-left: 200px;
         margin-top: 60px;
        /*position: fixed;*/
        /*left: 200px;*/
        /*top: 60px;*/
        /*width: 100%;*/
        /*height: 100%;*/
        overflow-y: auto;
        overflow-x: auto;
    }
    .nav-img {
        height: 18px;
    }
    .right-style {
        margin-left: 200px;
        position: relative;
    }
    .el-header {
        background-color: #ffffff;
        color: #333;
        line-height: 60px;
    }

    .el-aside {
        color: #333;
    }

    .title-style {
        float: left;
        line-height: 58px;
    }

    .title-style img {
        height: 40px;
        vertical-align: middle;
        margin-top: -2px;
    }

    .title-style span {
        padding-left: 20px;
    }

    .icon-style {
        display: inline-block;
        margin-right: 5px;
        margin-left: 20px;
        opacity: 0.5;
    }

    .icon-style:hover {
        display: inline-block;
        margin-right: 5px;
        margin-left: 20px;
        opacity: 1;
    }

    .icon-style img {
        vertical-align: middle;
        margin-top: -3px;
    }

    .cursorLink {
        cursor:pointer;
    }

    .nameCursor {
        cursor:default
    }

</style>